import { defineStore } from "pinia";
import { store } from "@/store";
import asyncRoutes from "@/router/permisson-routes";
import commonRoutes from "@/router/routes";
import { login } from "@/api/user";
import { storage } from "@/utils/storage";
import router from "@/router";

export const useUserStore = defineStore({
  id: "app-user",
  state: (): any => ({
    token: storage.getToken(),
    userInfo: {},
    avatar: "",
    permissions: [],
    menus: [],
    addRoutes: [],
    theme: {
      token: {
        colorPrimary: "#008dff",
      },
    },
  }),
  getters: {
    getMenus(): any[] {
      return this.userInfo.token ? asyncRoutes.children : commonRoutes.children;
    },
    getTheme(): any[] {
      return this.theme;
    },
  },
  actions: {
    async handleLogin(data) {
      const userInfo = await login(data);
      storage.setToken(userInfo.token);
      storage.set("account", userInfo);
      this.userInfo = userInfo;
      router.addRoute(asyncRoutes);
    },
    getUserInfo() {
      let userInfo = storage.get("account");
      this.userInfo = userInfo || {};
      this.addRoutes = this.userInfo.token ? asyncRoutes : commonRoutes;
    },
    changeTheme(opts) {
      this.theme.token = Object.assign(this.theme.token, opts);
    },
  },
  // 开启数据缓存
  persist: {
    enabled: true,
  },
});

// Need to be used outside the setup
export function useUserStoreWidthOut() {
  return useUserStore(store);
}
